package com.tbit.uqbike.client.controller;

import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.client.constant.RechargeConstant;
import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.constant.annotation.PreventDuplication;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.pojo.payPal.PayPalEntity;
import com.tbit.uqbike.client.service.PayPalService;
import com.tbit.uqbike.client.service.RedisService;
import com.tbit.uqbike.client.service.TokenService;
import com.tbit.uqbike.client.util.Assert;
import com.tbit.uqbike.client.util.LogUtil;
import com.tbit.uqbike.client.util.OutputUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 国际支付
 *
 * @Author: chen
 * @Description: 国际支付
 * @Date: 创建于 13:58 2020/1/10
 */
@Controller
@Slf4j
@RequestMapping("/payPal")
public class PayPalController {

    @Autowired
    private PayPalService payPalService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisService redisService;

    /**
     * 创建paypal APP支付订单-充值/交押金
     *
     * @param payPalEntity 充值实体类
     * @param adAccountId  区域id
     * @param response     返回
     * @ignoreParams request
     */
    @RequestMapping("/createOrder")
    @PreventDuplication(expireSeconds = 5)
    public void createOrder(PayPalEntity payPalEntity, Integer adAccountId, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (!payPalEntity.getDeposit()) {
                /* 校验 */
                Assert.notNull(payPalEntity.getMoney(), "-70001", "充值金额不能为空");
                User user = tokenService.getUser(payPalEntity.getToken());
                payPalEntity.setRechargeType(RechargeConstant.recharge_pay);
                redisService.add(user.getUserId() + ".agentId", String.valueOf(payPalEntity.getAdAccountId()), 600);
            } else {
                Assert.notNull(payPalEntity.getAdAccountId(), "-10001", "代理id不能为空");
                payPalEntity.setRechargeType(RechargeConstant.recharge_pay);
            }
            log.info("用户发起充值订单" + payPalEntity.getToken());
            map = payPalService.getOrder(payPalEntity, adAccountId);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 支付成功回调地址
     *
     * @param request
     * @param response
     * @ignore
     */
    @RequestMapping("/callback")
    public void callBack(HttpServletRequest request, HttpServletResponse response) {
        try {
            log.info("paypal回调了。。。。。。");
            String result = payPalService.callBack(request, response);
            OutputUtil.renderHtml(request, response, result);
        } catch (BaseException e) {
            log.error(e.getMessage(), e);
            OutputUtil.renderHtml(request, response, "fail");
        }
    }

    /**
     * 来自app的回调-验证支付有效性
     *
     * @param token     token
     * @param orderNO   订单编号
     * @param money     金额
     * @param orderId   订单id
     * @param accountId 品牌id
     * @param response  返回
     * @ignoreParams request
     * @ignore
     */
    @RequestMapping("/callBackFromApp")
    public void callBackFromApp(String token, String orderNO, Double money, String orderId, Integer accountId,
                                HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = payPalService.callBackFromApp(token, orderNO, money, orderId, accountId);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        LogUtil.info("返回信息==================：" + JSONObject.toJSONString(map));
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 创建免押会员订单
     *
     * @param payPalEntity 支付实体类
     * @param memberFeeId  免押会员id
     * @param response     返回
     * @ignoreParams request
     */
    @RequestMapping("/createOrder_memberFee")
    @PreventDuplication(expireSeconds = 5)
    public void createOrder_memberFee(PayPalEntity payPalEntity, Integer memberFeeId, Integer adAccountId, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {

            /* 校验 */
            Assert.notNull(memberFeeId, "-130003", "memberFeeId不能为空");
            Assert.notNull(payPalEntity.getAdAccountId(), "-10001", "区域id不能为空");
            payPalEntity.setRechargeType(RechargeConstant.recharge_Mem);
            User user = tokenService.getUser(payPalEntity.getToken());
            redisService.add(user.getUserId() + ".agentId", String.valueOf(payPalEntity.getAdAccountId()), 600);
            map = payPalService.createOrder_memberFee(payPalEntity, memberFeeId, adAccountId);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 创建骑行会员订单
     *
     * @param payPalEntity 支付实体类
     * @param rideCardId   骑行会员id
     * @param response     返回
     * @ignoreParams request
     */
    @RequestMapping("/createOrder_rideCard")
    @PreventDuplication(expireSeconds = 5)
    public void createOrder_rideCard(PayPalEntity payPalEntity, Integer rideCardId, Integer adAccountId, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {

            /* 校验 */
            Assert.notNull(rideCardId, "-120001", "骑行会员卡id不能为空");
            Assert.notNull(payPalEntity.getAdAccountId(), "-10001", "区域id不能为空");
            payPalEntity.setRechargeType(RechargeConstant.recharge_rideCard);
            User user = tokenService.getUser(payPalEntity.getToken());
            redisService.add(user.getUserId() + ".agentId", String.valueOf(payPalEntity.getAdAccountId()), 600);
            map = payPalService.createOrder_rideCard(payPalEntity, rideCardId, adAccountId);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 创建vip会员订单
     *
     * @param payPalEntity 支付实体类
     * @param vipId        会员卡id
     * @param response     响应
     * @ignoreParams request
     */
    @RequestMapping("/createOrder_vipOrder")
    @PreventDuplication(expireSeconds = 5)
    public void createOrder_vipOrder(
            PayPalEntity payPalEntity, Integer vipId, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {

            /* 校验 */
            Assert.notNull(vipId, "-120004", "会员卡id不能为空");
            Assert.notNull(payPalEntity.getAdAccountId(), "-10001", "区域id不能为空");
            payPalEntity.setRechargeType(RechargeConstant.recharge_vip);
            User user = tokenService.getUser(payPalEntity.getToken());
            redisService.add(user.getUserId() + ".agentId", String.valueOf(payPalEntity.getAdAccountId()), 600);
            map = payPalService.createOrder_vipOrder(payPalEntity, vipId, payPalEntity.getAdAccountId());
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 贝宝通知
     *
     * @param body     数据包
     * @param response 响应
     * @return {@link String}
     * @ignoreParams request
     * @ignore
     */
    @RequestMapping("/paypalNotify")
    public String paypalNotify(@RequestBody(required = false) byte[] body, HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        JSONObject rsJson = new JSONObject();
        System.out.println("paypal回调");
        try {
            String bodyStr = null;
            JSONObject paramJson = null;
            try {
                bodyStr = new String(body, "utf-8");
                paramJson = JSONObject.parseObject(bodyStr);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            /**
             * PAYMENT.SALE.COMPLETED
             */
            if (paramJson != null) {
                String eventType = paramJson.getString("event_type");
                if ("PAYMENT.SALE.COMPLETED".equalsIgnoreCase(eventType)) {
                    //支付完成处理逻辑
                    JSONObject resourceJson = paramJson.getJSONObject("resource");
                    String orderNo = resourceJson.getString("invoice_number");
                    String paymentId = resourceJson.getString("parent_payment");
                    log.info(resourceJson.toJSONString());
                }
            }
            out = response.getWriter();
            rsJson.put("status", "200");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            rsJson.put("status", "500");
        }
        out.println(rsJson.toString());
        out.flush();
        out.close();
        return null;
    }

}
